<template>
  <div ref="mentionRef" class="user-mention">
    <!-- 输入区域 -->
    <div class="mention-input-wrapper">
      <div :class="{ 'has-mentions': hasMentions, 'is-focused': isFocused }" class="input-container">
        <!-- 富文本输入区域 -->
        <div
          ref="editableRef"
          :class="{ 'is-disabled': disabled }"
          :data-placeholder="placeholder"
          class="mention-editor"
          contenteditable
          @blur="handleBlur"
          @click="handleClick"
          @focus="handleFocus"
          @input="handleInput"
          @keydown="handleKeyDown"
        ></div>

        <!-- 字符计数器 -->
        <div v-if="showCounter" :class="{ 'warning': isNearLimit, 'error': isOverLimit }" class="char-counter">
          {{ currentLength }}/{{ maxLength }}
        </div>
      </div>
    </div>

    <!-- 用户建议列表 -->
    <div
      v-if="showSuggestions && filteredUsers.length > 0"
      :style="suggestionStyle"
      class="mention-suggestions"
    >
      <div class="suggestions-header">
        <span class="suggestions-title">选择要@的用户</span>
        <span class="suggestions-count">({{ filteredUsers.length }})</span>
      </div>

      <div class="suggestions-list">
        <div
          v-for="(user, index) in filteredUsers"
          :key="user.id"
          :class="{
            'is-active': index === activeIndex,
            'is-selected': selectedUsers.has(user.id)
          }"
          class="suggestion-item"
          @click="selectUser(user, index)"
          @mouseenter="activeIndex = index"
        >
          <div class="user-avatar">
            <img v-if="user.avatar" :alt="user.name" :src="user.avatar" />
            <div v-else class="avatar-placeholder">
              {{ user.name.charAt(0) }}
            </div>
            <div v-if="user.isOnline" class="online-indicator"></div>
          </div>

          <div class="user-info">
            <div class="user-name">
              <span v-html="highlightMatch(user.name, searchQuery)"></span>
              <span v-if="user.isVerified" class="verified-badge">
                <svg fill="none" viewBox="0 0 24 24">
                  <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" stroke="currentColor" stroke-width="2"/>
                </svg>
              </span>
            </div>
            <div class="user-meta">
              <span class="user-relation">{{ user.relation }}</span>
              <span v-if="user.department" class="user-department">{{ user.department }}</span>
            </div>
          </div>

          <div class="user-actions">
            <div v-if="user.mutualConnections > 0" class="mutual-connections">
              {{ user.mutualConnections }}个共同联系人
            </div>
            <div class="selection-indicator">
              <svg v-if="selectedUsers.has(user.id)" fill="none" viewBox="0 0 24 24">
                <circle cx="12" cy="12" fill="currentColor" r="10"/>
                <path d="m9 12 2 2 4-4" stroke="white" stroke-width="2"/>
              </svg>
              <svg v-else fill="none" viewBox="0 0 24 24">
                <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
              </svg>
            </div>
          </div>
        </div>
      </div>

      <!-- 快捷操作 -->
      <div class="suggestions-footer">
        <div class="quick-actions">
          <button class="quick-action" @click="mentionAll">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" stroke="currentColor" stroke-width="2"/>
              <circle cx="9" cy="7" r="4" stroke="currentColor" stroke-width="2"/>
              <path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75" stroke="currentColor" stroke-width="2"/>
            </svg>
            @所有人
          </button>
          <button class="quick-action" @click="mentionOnline">
            <svg fill="none" viewBox="0 0 24 24">
              <circle cx="12" cy="12" fill="currentColor" r="3"/>
              <path d="m6.05 6.05 12.9 12.9m-12.9 0 12.9-12.9" stroke="currentColor" stroke-width="2"/>
            </svg>
            @在线成员
          </button>
        </div>

        <div class="navigation-hint">
          <span>↑↓ 选择</span>
          <span>Enter 确认</span>
          <span>Esc 取消</span>
        </div>
      </div>
    </div>

    <!-- 已提及用户列表 -->
    <div v-if="showMentionedUsers && mentionedUsers.length > 0" class="mentioned-users">
      <div class="mentioned-header">
        <span class="mentioned-title">已@用户</span>
        <button class="clear-all-btn" @click="clearAllMentions">
          <svg fill="none" viewBox="0 0 24 24">
            <line stroke="currentColor" stroke-width="2" x1="18" x2="6" y1="6" y2="18"/>
            <line stroke="currentColor" stroke-width="2" x1="6" x2="18" y1="6" y2="18"/>
          </svg>
          清除所有
        </button>
      </div>

      <div class="mentioned-list">
        <div
          v-for="user in mentionedUsers"
          :key="user.id"
          class="mentioned-user"
        >
          <div class="user-avatar">
            <img v-if="user.avatar" :alt="user.name" :src="user.avatar" />
            <div v-else class="avatar-placeholder">
              {{ user.name.charAt(0) }}
            </div>
          </div>

          <div class="user-info">
            <div class="user-name">{{ user.name }}</div>
            <div class="user-relation">{{ user.relation }}</div>
          </div>

          <button class="remove-mention-btn" @click="removeMention(user.id)">
            <svg fill="none" viewBox="0 0 24 24">
              <line stroke="currentColor" stroke-width="2" x1="18" x2="6" y1="6" y2="18"/>
              <line stroke="currentColor" stroke-width="2" x1="6" x2="18" y1="6" y2="18"/>
            </svg>
          </button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-overlay">
      <div class="loading-spinner">
        <svg fill="none" viewBox="0 0 24 24">
          <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
          <path d="M12 6v6l4 2" stroke="currentColor" stroke-width="2"/>
        </svg>
      </div>
      <span>搜索用户中...</span>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'

// Props
interface Props {
  modelValue?: string
  placeholder?: string
  disabled?: boolean
  maxLength?: number
  showCounter?: boolean
  showMentionedUsers?: boolean
  allowMultipleMentions?: boolean
  minSearchLength?: number
  maxSuggestions?: number
  searchDelay?: number
  customUsers?: User[]
  mentionTrigger?: string
  caseSensitive?: boolean
  allowSelfMention?: boolean
}

interface User {
  id: number
  name: string
  username?: string
  avatar?: string
  email?: string
  relation: string
  department?: string
  isOnline?: boolean
  isVerified?: boolean
  mutualConnections?: number
  lastSeen?: string
}

interface MentionRange {
  start: number
  end: number
  userId: number
  userName: string
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  placeholder: '输入 @ 来提及用户...',
  disabled: false,
  maxLength: 1000,
  showCounter: true,
  showMentionedUsers: true,
  allowMultipleMentions: true,
  minSearchLength: 1,
  maxSuggestions: 8,
  searchDelay: 300,
  mentionTrigger: '@',
  caseSensitive: false,
  allowSelfMention: false
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: string]
  'mention-added': [user: User]
  'mention-removed': [userId: number]
  'mentions-changed': [mentions: User[]]
  'search': [query: string]
  'focus': []
  'blur': []
}>()

// 响应式数据
const mentionRef = ref<HTMLElement>()
const editableRef = ref<HTMLElement>()
const isFocused = ref(false)
const showSuggestions = ref(false)
const isLoading = ref(false)
const searchQuery = ref('')
const activeIndex = ref(0)
const cursorPosition = ref(0)
const searchTimeout = ref<NodeJS.Timeout>()

const users = ref<User[]>([])
const selectedUsers = ref(new Set<number>())
const mentionedUsers = ref<User[]>([])
const mentionRanges = ref<MentionRange[]>([])

const suggestionStyle = ref({
  top: '0px',
  left: '0px'
})

const currentUser = ref<User>({
  id: 1,
  name: '我',
  username: 'me',
  relation: '自己'
})

// 计算属性
const currentLength = computed(() => {
  return props.modelValue?.length || 0
})

const isNearLimit = computed(() => {
  return currentLength.value > props.maxLength * 0.8
})

const isOverLimit = computed(() => {
  return currentLength.value > props.maxLength
})

const hasMentions = computed(() => {
  return mentionedUsers.value.length > 0
})

const filteredUsers = computed(() => {
  if (!searchQuery.value) return []

  const query = props.caseSensitive ? searchQuery.value : searchQuery.value.toLowerCase()

  let filtered = users.value.filter(user => {
    if (!props.allowSelfMention && user.id === currentUser.value.id) return false

    const name = props.caseSensitive ? user.name : user.name.toLowerCase()
    const username = user.username ? (props.caseSensitive ? user.username : user.username.toLowerCase()) : ''

    return name.includes(query) || username.includes(query)
  })

  // 排序：精确匹配 > 开头匹配 > 包含匹配
  filtered.sort((a, b) => {
    const aName = props.caseSensitive ? a.name : a.name.toLowerCase()
    const bName = props.caseSensitive ? b.name : b.name.toLowerCase()

    if (aName === query) return -1
    if (bName === query) return 1
    if (aName.startsWith(query) && !bName.startsWith(query)) return -1
    if (bName.startsWith(query) && !aName.startsWith(query)) return 1

    return a.name.localeCompare(b.name)
  })

  return filtered.slice(0, props.maxSuggestions)
})

// 方法
const handleInput = () => {
  const content = editableRef.value?.textContent || ''
  emit('update:modelValue', content)

  checkForMentions(content)
}

const handleFocus = () => {
  isFocused.value = true
  emit('focus')
}

const handleBlur = () => {
  // 延迟隐藏建议，允许点击建议项
  setTimeout(() => {
    isFocused.value = false
    showSuggestions.value = false
    emit('blur')
  }, 200)
}

const handleClick = () => {
  updateCursorPosition()
}

const handleKeyDown = (e: KeyboardEvent) => {
  if (showSuggestions.value && filteredUsers.value.length > 0) {
    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault()
        activeIndex.value = Math.min(activeIndex.value + 1, filteredUsers.value.length - 1)
        break
      case 'ArrowUp':
        e.preventDefault()
        activeIndex.value = Math.max(activeIndex.value - 1, 0)
        break
      case 'Enter':
        e.preventDefault()
        if (filteredUsers.value[activeIndex.value]) {
          selectUser(filteredUsers.value[activeIndex.value], activeIndex.value)
        }
        break
      case 'Escape':
        e.preventDefault()
        showSuggestions.value = false
        searchQuery.value = ''
        break
    }
  }

  // 限制字符长度
  if (currentLength.value >= props.maxLength && e.key.length === 1) {
    e.preventDefault()
  }
}

const checkForMentions = (content: string) => {
  const selection = window.getSelection()
  if (!selection || selection.rangeCount === 0) return

  const range = selection.getRangeAt(0)
  const textBeforeCursor = content.substring(0, range.startOffset)

  // 查找最后一个 @ 符号
  const lastAtIndex = textBeforeCursor.lastIndexOf(props.mentionTrigger)

  if (lastAtIndex !== -1) {
    const textAfterAt = textBeforeCursor.substring(lastAtIndex + 1)

    // 检查 @ 后面是否有空格或特殊字符
    if (!textAfterAt.includes(' ') && !textAfterAt.includes('\n')) {
      if (textAfterAt.length >= props.minSearchLength) {
        searchQuery.value = textAfterAt
        searchUsers(textAfterAt)
        updateSuggestionPosition()
        showSuggestions.value = true
        activeIndex.value = 0
      } else if (textAfterAt.length === 0) {
        searchQuery.value = ''
        loadAllUsers()
        updateSuggestionPosition()
        showSuggestions.value = true
        activeIndex.value = 0
      }
    } else {
      showSuggestions.value = false
      searchQuery.value = ''
    }
  } else {
    showSuggestions.value = false
    searchQuery.value = ''
  }
}

const searchUsers = async (query: string) => {
  if (searchTimeout.value) {
    clearTimeout(searchTimeout.value)
  }

  searchTimeout.value = setTimeout(async () => {
    try {
      isLoading.value = true
      emit('search', query)

      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))

      // 使用自定义用户列表或默认用户列表
      if (props.customUsers) {
        users.value = props.customUsers
      } else {
        users.value = await fetchUsers(query)
      }

    } catch (error) {
      console.error('Search users failed:', error)
    } finally {
      isLoading.value = false
    }
  }, props.searchDelay)
}

const loadAllUsers = async () => {
  try {
    isLoading.value = true

    if (props.customUsers) {
      users.value = props.customUsers
    } else {
      users.value = await fetchUsers('')
    }
  } catch (error) {
    console.error('Load users failed:', error)
  } finally {
    isLoading.value = false
  }
}

const fetchUsers = async (query: string): Promise<User[]> => {
  // 模拟用户数据
  const mockUsers: User[] = [
    {
      id: 2,
      name: '张小明',
      username: 'zhangxiaoming',
      avatar: '/images/avatars/user2.jpg',
      relation: '家庭成员',
      department: '技术部',
      isOnline: true,
      isVerified: true,
      mutualConnections: 5
    },
    {
      id: 3,
      name: '李小红',
      username: 'lixiaohong',
      avatar: '/images/avatars/user3.jpg',
      relation: '朋友',
      department: '产品部',
      isOnline: false,
      isVerified: false,
      mutualConnections: 3
    },
    {
      id: 4,
      name: '王大华',
      username: 'wangdahua',
      avatar: '/images/avatars/user4.jpg',
      relation: '同事',
      department: '设计部',
      isOnline: true,
      isVerified: true,
      mutualConnections: 8
    },
    {
      id: 5,
      name: '刘小芳',
      username: 'liuxiaofang',
      avatar: '/images/avatars/user5.jpg',
      relation: '邻居',
      isOnline: false,
      isVerified: false,
      mutualConnections: 1
    }
  ]

  return mockUsers
}

const selectUser = (user: User, index: number) => {
  if (!editableRef.value) return

  const content = editableRef.value.textContent || ''
  const lastAtIndex = content.lastIndexOf(props.mentionTrigger, cursorPosition.value)

  if (lastAtIndex !== -1) {
    const beforeAt = content.substring(0, lastAtIndex)
    const afterMention = content.substring(cursorPosition.value)

    const mentionText = `${props.mentionTrigger}${user.name} `
    const newContent = beforeAt + mentionText + afterMention

    editableRef.value.textContent = newContent
    emit('update:modelValue', newContent)

    // 更新光标位置
    const newCursorPos = lastAtIndex + mentionText.length
    setCursorPosition(newCursorPos)

    // 添加到已提及用户列表
    if (!selectedUsers.value.has(user.id)) {
      selectedUsers.value.add(user.id)
      mentionedUsers.value.push(user)

      // 记录提及范围
      mentionRanges.value.push({
        start: lastAtIndex,
        end: lastAtIndex + mentionText.length - 1,
        userId: user.id,
        userName: user.name
      })

      emit('mention-added', user)
      emit('mentions-changed', mentionedUsers.value)
    }
  }

  showSuggestions.value = false
  searchQuery.value = ''
  editableRef.value.focus()
}

const removeMention = (userId: number) => {
  const userIndex = mentionedUsers.value.findIndex(u => u.id === userId)
  if (userIndex !== -1) {
    const user = mentionedUsers.value[userIndex]
    mentionedUsers.value.splice(userIndex, 1)
    selectedUsers.value.delete(userId)

    // 从内容中移除提及
    removeMentionFromContent(user.name)

    emit('mention-removed', userId)
    emit('mentions-changed', mentionedUsers.value)
  }
}

const removeMentionFromContent = (userName: string) => {
  if (!editableRef.value) return

  const content = editableRef.value.textContent || ''
  const mentionPattern = new RegExp(`${props.mentionTrigger}${userName}\\s?`, 'g')
  const newContent = content.replace(mentionPattern, '')

  editableRef.value.textContent = newContent
  emit('update:modelValue', newContent)
}

const clearAllMentions = () => {
  mentionedUsers.value = []
  selectedUsers.value.clear()
  mentionRanges.value = []

  if (editableRef.value) {
    const content = editableRef.value.textContent || ''
    const mentionPattern = new RegExp(`${props.mentionTrigger}\\w+\\s?`, 'g')
    const newContent = content.replace(mentionPattern, '')

    editableRef.value.textContent = newContent
    emit('update:modelValue', newContent)
  }

  emit('mentions-changed', [])
}

const mentionAll = () => {
  // 实现 @所有人 功能
  const allUser: User = {
    id: -1,
    name: '所有人',
    username: 'everyone',
    relation: '全员'
  }
  selectUser(allUser, 0)
}

const mentionOnline = () => {
  // 实现 @在线成员 功能
  const onlineUser: User = {
    id: -2,
    name: '在线成员',
    username: 'online',
    relation: '在线用户'
  }
  selectUser(onlineUser, 0)
}

const updateCursorPosition = () => {
  const selection = window.getSelection()
  if (selection && selection.rangeCount > 0) {
    cursorPosition.value = selection.getRangeAt(0).startOffset
  }
}

const setCursorPosition = (position: number) => {
  if (!editableRef.value) return

  const range = document.createRange()
  const selection = window.getSelection()

  if (editableRef.value.childNodes.length > 0) {
    range.setStart(editableRef.value.childNodes[0], Math.min(position, editableRef.value.textContent?.length || 0))
  } else {
    range.setStart(editableRef.value, 0)
  }

  range.collapse(true)
  selection?.removeAllRanges()
  selection?.addRange(range)
}

const updateSuggestionPosition = () => {
  if (!editableRef.value) return

  nextTick(() => {
    const rect = editableRef.value!.getBoundingClientRect()
    suggestionStyle.value = {
      top: `${rect.bottom + 8}px`,
      left: `${rect.left}px`
    }
  })
}

const highlightMatch = (text: string, query: string): string => {
  if (!query) return text

  const searchText = props.caseSensitive ? text : text.toLowerCase()
  const searchQuery = props.caseSensitive ? query : query.toLowerCase()

  const index = searchText.indexOf(searchQuery)
  if (index === -1) return text

  const beforeMatch = text.substring(0, index)
  const match = text.substring(index, index + query.length)
  const afterMatch = text.substring(index + query.length)

  return `${beforeMatch}<mark>${match}</mark>${afterMatch}`
}

// 监听器
watch(() => props.modelValue, (newValue) => {
  if (editableRef.value && editableRef.value.textContent !== newValue) {
    editableRef.value.textContent = newValue || ''
  }
})

// 生命周期
onMounted(() => {
  if (props.modelValue) {
    editableRef.value!.textContent = props.modelValue
  }

  // 点击外部关闭建议
  document.addEventListener('click', (e) => {
    if (!mentionRef.value?.contains(e.target as Node)) {
      showSuggestions.value = false
    }
  })
})

onUnmounted(() => {
  if (searchTimeout.value) {
    clearTimeout(searchTimeout.value)
  }
})

// 暴露给父组件的方法
defineExpose({
  focus: () => editableRef.value?.focus(),
  blur: () => editableRef.value?.blur(),
  clear: () => {
    if (editableRef.value) {
      editableRef.value.textContent = ''
      emit('update:modelValue', '')
    }
  },
  insertMention: selectUser,
  getMentions: () => mentionedUsers.value,
  clearMentions: clearAllMentions
})
</script>

<style lang="scss" scoped>
.user-mention {
  position: relative;

  .mention-input-wrapper {
    .input-container {
      position: relative;
      border: 1px solid #d1d5db;
      border-radius: 8px;
      background: white;
      transition: all 0.2s ease;

      &.is-focused {
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
      }

      &.has-mentions {
        border-color: #10b981;
        background: #f0fdf4;
      }

      .mention-editor {
        min-height: 100px;
        max-height: 200px;
        padding: 0.75rem;
        outline: none;
        font-size: 0.9rem;
        line-height: 1.5;
        overflow-y: auto;
        word-wrap: break-word;
        white-space: pre-wrap;

        &.is-disabled {
          opacity: 0.6;
          cursor: not-allowed;
        }

        &:empty::before {
          content: attr(data-placeholder);
          color: #9ca3af;
          pointer-events: none;
        }

        :deep(.mention-highlight) {
          background: #dbeafe;
          color: #1d4ed8;
          border-radius: 4px;
          padding: 0.125rem 0.25rem;
          font-weight: 500;
        }
      }

      .char-counter {
        position: absolute;
        bottom: 0.5rem;
        right: 0.75rem;
        font-size: 0.75rem;
        color: #9ca3af;
        pointer-events: none;

        &.warning {
          color: #f59e0b;
        }

        &.error {
          color: #ef4444;
        }
      }
    }
  }

  .mention-suggestions {
    position: fixed;
    background: white;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
    z-index: 50;
    min-width: 300px;
    max-width: 400px;
    max-height: 400px;
    overflow: hidden;
    animation: slideDown 0.2s ease-out;

    .suggestions-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0.75rem 1rem;
      border-bottom: 1px solid #f1f5f9;
      background: #f8fafc;

      .suggestions-title {
        font-size: 0.85rem;
        font-weight: 600;
        color: #374151;
      }

      .suggestions-count {
        font-size: 0.75rem;
        color: #6b7280;
      }
    }

    .suggestions-list {
      max-height: 280px;
      overflow-y: auto;

      .suggestion-item {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        padding: 0.75rem 1rem;
        cursor: pointer;
        transition: all 0.2s ease;

        &:hover,
        &.is-active {
          background: #f9fafb;
        }

        &.is-selected {
          background: #eff6ff;
          border-left: 3px solid #3b82f6;
        }

        .user-avatar {
          position: relative;
          width: 40px;
          height: 40px;
          border-radius: 50%;
          overflow: hidden;
          flex-shrink: 0;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .avatar-placeholder {
            width: 100%;
            height: 100%;
            background: #e5e7eb;
            color: #6b7280;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
          }

          .online-indicator {
            position: absolute;
            bottom: 2px;
            right: 2px;
            width: 10px;
            height: 10px;
            background: #10b981;
            border: 2px solid white;
            border-radius: 50%;
          }
        }

        .user-info {
          flex: 1;
          min-width: 0;

          .user-name {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-weight: 500;
            color: #374151;
            margin-bottom: 0.125rem;

            :deep(mark) {
              background: #fef3c7;
              color: #92400e;
              padding: 0.125rem;
              border-radius: 3px;
            }

            .verified-badge {
              color: #059669;

              svg {
                width: 16px;
                height: 16px;
              }
            }
          }

          .user-meta {
            display: flex;
            gap: 0.75rem;
            font-size: 0.8rem;
            color: #6b7280;

            .user-relation {
              font-weight: 500;
            }

            .user-department {
              opacity: 0.8;
            }
          }
        }

        .user-actions {
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          gap: 0.25rem;

          .mutual-connections {
            font-size: 0.7rem;
            color: #6b7280;
            white-space: nowrap;
          }

          .selection-indicator {
            svg {
              width: 18px;
              height: 18px;
              color: #3b82f6;
            }
          }
        }
      }
    }

    .suggestions-footer {
      border-top: 1px solid #f1f5f9;
      padding: 0.75rem 1rem;

      .quick-actions {
        display: flex;
        gap: 0.5rem;
        margin-bottom: 0.5rem;

        .quick-action {
          display: flex;
          align-items: center;
          gap: 0.5rem;
          padding: 0.375rem 0.75rem;
          background: #f3f4f6;
          border: none;
          border-radius: 6px;
          color: #374151;
          font-size: 0.8rem;
          cursor: pointer;
          transition: all 0.2s ease;

          &:hover {
            background: #e5e7eb;
          }

          svg {
            width: 14px;
            height: 14px;
          }
        }
      }

      .navigation-hint {
        display: flex;
        gap: 1rem;
        font-size: 0.7rem;
        color: #9ca3af;

        span {
          display: flex;
          align-items: center;
          gap: 0.25rem;
        }
      }
    }
  }

  .mentioned-users {
    margin-top: 1rem;
    padding: 1rem;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;

    .mentioned-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 0.75rem;

      .mentioned-title {
        font-size: 0.9rem;
        font-weight: 600;
        color: #374151;
      }

      .clear-all-btn {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.25rem 0.5rem;
        background: transparent;
        border: none;
        color: #ef4444;
        font-size: 0.8rem;
        cursor: pointer;
        border-radius: 4px;
        transition: background 0.2s ease;

        &:hover {
          background: rgba(239, 68, 68, 0.1);
        }

        svg {
          width: 12px;
          height: 12px;
        }
      }
    }

    .mentioned-list {
      display: flex;
      flex-wrap: wrap;
      gap: 0.5rem;

      .mentioned-user {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.375rem 0.5rem;
        background: white;
        border: 1px solid #d1d5db;
        border-radius: 6px;

        .user-avatar {
          width: 24px;
          height: 24px;
          border-radius: 50%;
          overflow: hidden;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .avatar-placeholder {
            width: 100%;
            height: 100%;
            background: #e5e7eb;
            color: #6b7280;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.7rem;
          }
        }

        .user-info {
          .user-name {
            font-size: 0.8rem;
            font-weight: 500;
            color: #374151;
          }

          .user-relation {
            font-size: 0.7rem;
            color: #6b7280;
          }
        }

        .remove-mention-btn {
          width: 18px;
          height: 18px;
          border: none;
          background: transparent;
          color: #ef4444;
          cursor: pointer;
          border-radius: 3px;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: background 0.2s ease;

          &:hover {
            background: rgba(239, 68, 68, 0.1);
          }

          svg {
            width: 12px;
            height: 12px;
          }
        }
      }
    }
  }

  .loading-overlay {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.75rem;
    padding: 1rem;
    color: #6b7280;
    font-size: 0.9rem;

    .loading-spinner {
      svg {
        width: 20px;
        height: 20px;
        animation: spin 1s linear infinite;
      }
    }
  }
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

// 响应式设计
@media (max-width: 768px) {
  .user-mention {
    .mention-suggestions {
      position: fixed;
      left: 1rem !important;
      right: 1rem;
      top: auto !important;
      bottom: 1rem;
      max-width: none;
      width: auto;

      .suggestions-list .suggestion-item {
        padding: 0.5rem 0.75rem;

        .user-avatar {
          width: 36px;
          height: 36px;
        }

        .user-info .user-name {
          font-size: 0.85rem;
        }
      }

      .suggestions-footer .quick-actions {
        flex-direction: column;

        .quick-action {
          justify-content: center;
        }
      }
    }

    .mentioned-users .mentioned-list {
      gap: 0.375rem;

      .mentioned-user {
        flex: 1;
        min-width: 0;

        .user-info {
          min-width: 0;

          .user-name {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
    }
  }
}

// 暗色模式
@media (prefers-color-scheme: dark) {
  .user-mention {
    .input-container {
      background: #1f2937;
      border-color: #374151;
      color: #f9fafb;

      &.is-focused {
        border-color: #3b82f6;
      }

      &.has-mentions {
        border-color: #10b981;
        background: #064e3b;
      }

      .mention-editor:empty::before {
        color: #6b7280;
      }
    }

    .mention-suggestions {
      background: #1f2937;
      border-color: #374151;

      .suggestions-header {
        background: #111827;
        border-bottom-color: #374151;

        .suggestions-title {
          color: #f9fafb;
        }
      }

      .suggestion-item {
        &:hover,
        &.is-active {
          background: #374151;
        }

        .user-info .user-name {
          color: #f9fafb;
        }
      }
    }

    .mentioned-users {
      background: #111827;
      border-color: #374151;

      .mentioned-header .mentioned-title {
        color: #f9fafb;
      }

      .mentioned-list .mentioned-user {
        background: #1f2937;
        border-color: #374151;

        .user-info .user-name {
          color: #f9fafb;
        }
      }
    }
  }
}
</style>
